package com.crm.system.service.impl.contractReviewManager;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.PaymentMethodEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.model.entity.MessageManager.Message;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractReviewManager.ContractReview;
import com.crm.model.entity.couponManager.CouponIssued;
import com.crm.model.entity.couponManager.CustomerContractCoupon;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerProductDetailCoupon;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.messageprompt.MessagePrompt;
import com.crm.model.entity.opportunityManager.Opportunity;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.orderManager.CustomerProductOrderDetail;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.sys.FileUpload;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.contractManager.CustomerContractAddQO;
import com.crm.model.qo.contractReviewManager.ContractReviewFormQO;
import com.crm.model.qo.contractReviewManager.ContractReviewQO;
import com.crm.model.vo.announcement.AnnouncementVO;
import com.crm.model.vo.contractReviewManager.*;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.redis.service.returnMoneyManager.ReturnMoneyRedisService;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractReviewManager.ContractReviewDbService;
import com.crm.service.couponManager.ContractCouponDbService;
import com.crm.service.couponManager.CouponIssuedDbService;
import com.crm.service.csd.customerManager.ContractContactDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerSendCodeDbService;
import com.crm.service.messageManager.MessageDbService;
import com.crm.service.messageprompt.MessagePromptDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.returnMoney.ReturnMoneyDbservice;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.FileUploadService;
import com.crm.system.service.contractReviewManager.ContractReviewService;
import com.crm.system.service.impl.returnMoney.ReturnMoneyServiceImpl;
import com.crm.system.service.orderManager.CustomerProductOrderService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.annotation.Contract;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author luojie
 * @date 2021/3/30 11:26
 * (客服部)审核管理--合同审核
 */
@Service
@Slf4j
public class ContractReviewServiceImpl implements ContractReviewService {

    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private OpportunityDbService opportunityDbService;
    @Autowired
    private ClueFollowDbService followDbService;
    @Autowired
    private CustomerProductOrderDbService orderDbService;
    @Autowired
    private UserAccountDbService accountDbService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private ContractReviewDbService contractReviewDbService;
    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;
    @Autowired
    private ReturnMoneyService returnMoneyService;
    @Autowired
    private FinishOrderDBservice finishOrderDBservice;
    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerProductOrderDbService productOrderDbService;
    @Autowired
    private MessagePromptDbService messagePromptDbService;
    @Autowired
    private MessageDbService messageDbService;
    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;
    @Autowired
    private ReturnMoneyRedisService returnMoneyRedisService;
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;
    @Autowired
    private CustomerProductOrderService customerProductOrderService;

    @Autowired
    private CustomerSendCodeDbService customerSendCodeDbService;
    @Autowired
    private ContractCouponDbService contractCouponDbService;
    @Autowired
    private CouponIssuedDbService couponIssuedDbService;


    /**
     * 审核管理--合同审核列表
     * @param contractReviewFormQO   ---合同审核列表查询参数
     * @param pageIndex/ pageSize    ---页码、分页大小
     * @param sortName/sortOrder     ---排序字段及规则
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<ContractReviewFormVO>  selectContractReviewFormVOList(ContractReviewFormQO contractReviewFormQO,Integer pageIndex,Integer pageSize,String sortName,String sortOrder){
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer dateUnit = 0;

        if (!StringUtils.isBlank(contractReviewFormQO.getDateType())) {
            if ("today".equals(contractReviewFormQO.getDateType())) {
                //今天
                dateUnit = 1;
            }
            if ("thisWeek".equals(contractReviewFormQO.getDateType())) {
                //本周
                dateUnit = 2;
            }
            if ("thisMonth".equals(contractReviewFormQO.getDateType())) {
                //本月
                dateUnit = 3;
            }
        }

        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("createTm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }

        List<ContractReviewFormVO> contractReviewFormVOList = contractReviewDbService.selectContractReviewFormVOList(contractReviewFormQO,dateUnit,order.toString());
        PageInfo<ContractReviewFormVO> pageInfo = new PageInfo<ContractReviewFormVO>(contractReviewFormVOList);
        return new DhPageInfo<ContractReviewFormVO>(pageInfo, contractReviewFormVOList);
    }

    /**
     * 合同详情--审核详情(最新审核记录)
     * @param contractId ---合同ID
     * @author yincuimei
     * @return
     */
    @Override
    public ContractReviewVO selectContractReviewFinally(String contractId) {
        return contractReviewDbService.selectContractReviewFinally(contractId);
    }

    /***
     * @Description:根据合同id获取合同审核信息
     * @Param:  * @param contractId 合同id
     * @Author: luojie
     * @Date: 2021/3/30 14:37
     */
    @Override
    public ContractReviewDetailVO getContractReviewDetail(String contractId) {
        //查询合同基本信息
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        ContractReviewDetailVO contractReviewDetailVO = new ContractReviewDetailVO();
        contractReviewDetailVO.setContractId(customerContract.getContractId());
        contractReviewDetailVO.setContractNumber(customerContract.getContractNumber());
        contractReviewDetailVO.setContractType(customerContract.getContractType());
        contractReviewDetailVO.setCustomerName(customerContract.getCustomerName());
        contractReviewDetailVO.setContractStatus(customerContract.getContractStatus());
        contractReviewDetailVO.setContactName(customerContract.getContactName());
        contractReviewDetailVO.setContactDetails(customerContract.getContactDetails());
        contractReviewDetailVO.setCustomerEmail(customerContract.getCustomerEmail());
        contractReviewDetailVO.setContractStartDate(customerContract.getContractStartDate());
        contractReviewDetailVO.setContractEndDate(customerContract.getContractEndDate());
        contractReviewDetailVO.setPayBackDate(customerContract.getPayBackDate());
        contractReviewDetailVO.setCustomerId(customerContract.getCustomerId());
        contractReviewDetailVO.setApplyElectronicContract(customerContract.getApplyElectronicContract());
        contractReviewDetailVO.setContractReviewStatus(customerContract.getContractReviewStatus());
        if(!StringUtils.isBlank(customerContract.getPaymentMethod())){
            //支付方式--2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;6:微信支付;
            switch(customerContract.getPaymentMethod()){
                case "2" :
                    contractReviewDetailVO.setPaymentMethod("线下支付");
                    break;
                case "3" :
                    contractReviewDetailVO.setPaymentMethod("余额支付");
                    break;
                case "4" :
                    contractReviewDetailVO.setPaymentMethod("转入额支付");
                    break;
                case "5" :
                    contractReviewDetailVO.setPaymentMethod("余额+转入额");
                    break;
                case "6" :
                    contractReviewDetailVO.setFollowRecordName("微信支付");
                    break;
                default :
                    contractReviewDetailVO.setFollowRecordName("");
            }

        }


        //查询客户类型
        if(!StringUtils.isBlank(customerContract.getCustomerId())){
            Customer customer = customerDbService.selectCustomerById(customerContract.getCustomerId());
            if(customer!=null){
                contractReviewDetailVO.setCustomerType(customer.getCustomerType());
            }
        }


        //查询会员主合同的始末时间
        if(!StringUtils.isBlank(customerContract.getMasterMembershipContract())){
            CustomerContract contract = customerContractDbService.selectContractById(customerContract.getMasterMembershipContract());
            if(contract!=null){
                contractReviewDetailVO.setMasterMembershipContract(contract.getContractNumber());
                contractReviewDetailVO.setMasterMembershipContractId(contract.getContractId());
                contractReviewDetailVO.setMasterMembershipContractStartTime(contract.getContractStartDate());
                contractReviewDetailVO.setMasterMembershipContractEndTime(contract.getContractEndDate());

                if(!StringUtils.isBlank(contract.getOrderId())){
                    List<CustomerProductOrderDetail> productOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(contract.getOrderId(), "1");
                    contractReviewDetailVO.setProductOrderDetailList(productOrderDetailList);
                }
            }
        }

        //查询创建人姓名
        UserAccount account = accountDbService.selectUserAccountByAccountId(customerContract.getCreatePeopleId());
        contractReviewDetailVO.setCreatePeopleName(account.getUserName());
        contractReviewDetailVO.setCreateTm(customerContract.getCreateTm());
        Opportunity opportunity = opportunityDbService.selectByOpportunityId(customerContract.getOpportunityId());
        if(opportunity!=null){
            contractReviewDetailVO.setOpportunityName(opportunity.getOpportunityTitle());
            contractReviewDetailVO.setOpportunityId(customerContract.getOpportunityId());
        }

        contractReviewDetailVO.setFollowRecordId(customerContract.getFollowRecordId());
        //查询跟进记录
        ClueFollow clueFollow = followDbService.selectClueFollowById(customerContract.getFollowRecordId());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(clueFollow!=null){
            String createTmStr = formatter.format(clueFollow.getCreateTm());
            //跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
            switch(clueFollow.getFollowWay()){
                case 1 :
                    contractReviewDetailVO.setFollowRecordName("线上电话 "+createTmStr);
                    break;
                case 2 :
                    contractReviewDetailVO.setFollowRecordName("拜访 "+createTmStr);
                    break;
                case 3 :
                    contractReviewDetailVO.setFollowRecordName("微信 "+createTmStr);
                    break;
                case 4 :
                    contractReviewDetailVO.setFollowRecordName("线下电话 "+createTmStr);
                    break;
                case 5 :
                    contractReviewDetailVO.setFollowRecordName("邮箱 "+createTmStr);
                    break;
                case 6 :
                    contractReviewDetailVO.setFollowRecordName("陪访 "+createTmStr);
                    break;
                default :
                    contractReviewDetailVO.setOrderStatus("");
            }
        }
        contractReviewDetailVO.setAdvancePostponementReason(customerContract.getAdvancePostponementReason());
        contractReviewDetailVO.setContractTotalAmount(customerContract.getContractTotalAmount());
        contractReviewDetailVO.setContractDiscountTotalAmount(customerContract.getContractDiscountTotalAmount());
        contractReviewDetailVO.setContractReceivables(customerContract.getContractReceivables());
        contractReviewDetailVO.setContractActualTotalAmount(customerContract.getContractActualTotalAmount());
        //合同附件
        FileUpload fileUploadAnnex = fileUploadService.selectFileUploadById(customerContract.getContractAnnexId());
        if(fileUploadAnnex!=null){
            contractReviewDetailVO.setContractAnnexAccessUrl(fileUploadAnnex.getAccessUrl());
        }
        //审核附件
        FileUpload fileUploadReviewAnnex = fileUploadService.selectFileUploadById(customerContract.getReviewAnnexId());
        if(fileUploadReviewAnnex!=null){
            contractReviewDetailVO.setReviewAnnexAccessUrl(fileUploadReviewAnnex.getAccessUrl());
        }
        //补充附件
        FileUpload fileUploadReplenishAnnex = fileUploadService.selectFileUploadById(customerContract.getContractReplenishAnnex());
        if(fileUploadReplenishAnnex!=null){
            contractReviewDetailVO.setContractReplenishAnnexUrl(fileUploadReplenishAnnex.getAccessUrl());
        }
        contractReviewDetailVO.setContractReviewNotes(customerContract.getContractReviewNotes());
        //查询订单
        CustomerProductOrder customerProductOrder = orderDbService.selectCustomerProductOrderById(customerContract.getOrderId());
        if(customerProductOrder!=null){
            contractReviewDetailVO.setOrderNumber(customerProductOrder.getOrderNumber());
            contractReviewDetailVO.setOrderSurcharge(customerProductOrder.getOrderSurcharge());
            contractReviewDetailVO.setOrderSurchargeRemark(customerProductOrder.getOrderSurchargeRemark());
            switch(customerProductOrder.getOrderStatus()){
                case "1" :
                    contractReviewDetailVO.setOrderStatus("等待回款");
                    break;
                case "2" :
                    contractReviewDetailVO.setOrderStatus("已完成");
                    break;
                case "3" :
                    contractReviewDetailVO.setOrderStatus("作废");
                    break;
                case "4" :
                    contractReviewDetailVO.setOrderStatus("部分回款");
                    break;
                default :
                    contractReviewDetailVO.setOrderStatus("");
            }
        }
        return contractReviewDetailVO;
    }

    /***
     * @Description:新增合同审批
     * @Param: contractReviewQO 合同审批对象
     * @Author: luojie
     * @Date: 2021/3/31 10:44
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addContractReview(ContractReviewQO contractReviewQO) {
        //查询合同基本信息
        CustomerContract customerContract = customerContractDbService.selectContractById(contractReviewQO.getContractId());

        Date newDate = new Date();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        ContractReview contractReview = new ContractReview();
        contractReview.setContractReviewId(CommonUtils.getGUID());
        contractReview.setContractId(contractReviewQO.getContractId());
        contractReview.setProcessResult(contractReviewQO.getProcessResult());
        //如果合同审批结果
        contractReview.setContractReviewType(contractReviewQO.getContractReviewType());
        contractReview.setContractReviewNotes(contractReviewQO.getContractReviewNotes());
        contractReview.setCreatePeopleId(userAccount.getAccountId());
        contractReview.setCreateTm(newDate);
        Boolean result = contractReviewDbService.addContractReview(contractReview);


        if(result){
            //插入消息提示表
            MessagePrompt messagePrompt = new MessagePrompt();
            messagePrompt.setMessageId(CommonUtils.getGUID());
            //消息类型为审核
            messagePrompt.setMessageType(Short.parseShort("3"));
            messagePrompt.setMessageState(Short.parseShort("0"));
            String processResultValue = "";
            if("1".equals(contractReviewQO.getProcessResult())){
                processResultValue = "补充资料";
            }else if("2".equals(contractReviewQO.getProcessResult())){
                processResultValue = "审核通过";
            }else if("4".equals(contractReviewQO.getProcessResult())){
                processResultValue = "审核通过并盖章";
            }else {
                processResultValue = "审核未通过";

                //如果合同未通过更新商机表商机合同字段为0
                if(!StringUtils.isBlank(customerContract.getOpportunityId())){
                    Opportunity opportunity = new Opportunity();
                    opportunity.setOpportunityId(customerContract.getOpportunityId());
                    opportunity.setOpportunityContractType("0");
                    opportunity.setUpdateTm(new Date());
                    opportunity.setUpdatePeopleId(userAccount.getAccountId());
                    opportunityDbService.updateOpportunityId(opportunity);
                }

                //如果是补款升级合同，修改原合同已兑换的产品finish表修改成位兑换
                if("1".equals(customerContract.getContractOtherType())){
                    String finishOrderProductId = customerContract.getUpgradeRelateFinishProductId();
                    finishOrderDBservice.updateFinishOrderProductExchangeStatus(finishOrderProductId,"0");
                }

                //6、恢复客户关联优惠券使用状态
                List<CustomerContractCoupon> customerContractCouponList = contractCouponDbService.selectContractCouponByContractId(contractReviewQO.getContractId());
                customerContractCouponList.stream().forEach(contractCoupon -> {
                    CouponIssued couponIssued = new CouponIssued();
                    couponIssued.setReceiveCouponId(contractCoupon.getReceiveCouponId());
                    couponIssued.setUsed(Short.parseShort("0"));
                    couponIssued.setUpdatePeopleId(userAccount.getAccountId());
                    couponIssued.setUpdateTm(new Date());
                    couponIssuedDbService.updateCouponIssuedById(couponIssued);
                });
            }
            messagePrompt.setMessageContent("您的合同编号" + customerContract.getContractNumber()  + "已审批，结果：" + processResultValue);
            messagePrompt.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            messagePrompt.setCreatePeopleId(userAccount.getAccountId());
            messagePrompt.setCreateTm(new Date());
            messagePrompt.setUpdatePeopleId(userAccount.getAccountId());
            messagePrompt.setUpdateTm(new Date());
            messagePromptDbService.insertMessagePrompt(messagePrompt);

            // 插入系统消息表
            Message message = new Message();
            message.setMessageId(CommonUtils.getGUID());

            // TODO: 2021年11月12日  因“消息主题”还未明确阈值，暂时存储当前业务类型
            message.setThemeId(CommonUtils.getGUID());
            message.setTheme("合同审核");
            message.setSendCompanyId(userAccount.getCompanyId());
            message.setSenderId(userAccount.getAccountId());
            String messageContent = "您的合同编号" + "<a class=\"js-create-tab\" data-title=\"合同详情\" data-url=\"/front/contractManager/contractDetail?contractId=" + customerContract.getContractId() + "&urlType=1" + "\">\n"
                                           + "<span class=\"text\">" + customerContract.getContractNumber() + "</span>\n"
                                           + "</a>\n" + "已审批，结果：" + processResultValue;
            message.setNewsDetail(messageContent);
            message.setSendTm(new Date());
            message.setNewsType(4); // 4: 系统消息
            message.setReceiverCompanyId(customerContract.getAffiliationCompanyId());
            message.setReceiverId(customerContract.getCreatePeopleId());
            message.setReceiverTm(new Date());
            message.setCreateTm(new Date());
            message.setUpdateTm(new Date());
            message.setCreatePeopleId(userAccount.getAccountId());
            message.setpMessageId(messagePrompt.getMessageId());
            messageDbService.addMessage(message);
        }

        //更新合同表的审核结果
        //更新合同表的审核结果（包括审核不通过时修改合同状态为已作废）
        Boolean updateContract = customerContractDbService.updateContractReviewStatus(contractReviewQO.getContractId(),contractReviewQO.getProcessResult(),userAccount.getAccountId(),userAccount.getUserName(),contractReviewQO.getContractReviewNotes(),newDate);

        //审核不通过时修改订单,更新订单为已作废
        if("3".equals(contractReviewQO.getProcessResult())){
            CustomerProductOrder customerProductOrder = new CustomerProductOrder();
            customerProductOrder.setProductOrderId(customerContract.getOrderId());
            customerProductOrder.setOrderStatus("3");
            customerProductOrderDbService.updateProductOrder(customerProductOrder);
        }

        //如果审核不通过，商机状态设置为可创建
        //3：将合同绑定的商机表的合同商机置改成未创建
/*        if("3".equals(contractReviewQO.getProcessResult())){
            Opportunity opportunity = new Opportunity();
            opportunity.setOpportunityId(customerContract.getOpportunityId());
            opportunity.setOpportunityContractType("0");
            opportunity.setUpdateTm(new Date());
            opportunity.setUpdatePeopleId(userAccount.getAccountId());
            opportunityDbService.updateOpportunityId(opportunity);
        }*/

        //合同支付方式
        String paymentMethod = customerContract.getPaymentMethod();
        BigDecimal contractReceivables = customerContract.getContractReceivables();
        //合同不是线下支付，且审核不通过修改合同和订单状态并将前原路返回
        if((!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod))&&"3".equals(contractReviewQO.getProcessResult())){

            //查询客户信息
            Customer customerOld = customerDbService.selectCustomerById(customerContract.getCustomerId());
            Customer customerNew = new Customer();
            customerNew.setCustomerId(customerContract.getCustomerId());
            //钱原路返回
            //2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;
            switch (paymentMethod) {
                case "3": {
                    customerNew.setCustomerWallet(customerOld.getCustomerWallet().add(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);
                    break;
                }
                case "4": {
                    customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().add(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);
                    break;
                }
/*                case "5": {
                    if (customerOld.getCustomerShiftWallet().compareTo(contractReceivables) == -1) {
                        customerNew.setCustomerShiftWallet(BigDecimal.valueOf(0));
                        customerNew.setCustomerWallet(contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    } else {
                        customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    }
                    customerDbService.updateCustomerById(customerNew);
                    break;
                }*/
                default:
                    break;
            }

        }

        //审核通过并且是余额支付
        if((!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(customerContract.getPaymentMethod()))&&("2".equals(contractReviewQO.getProcessResult())||"4".equals(contractReviewQO.getProcessResult()))){
            switch (paymentMethod) {
                case "3": {
                    //插入回款表
                    returnMoney(customerContract.getContractType(),contractReceivables,customerContract.getContractId(),
                            customerContract.getOrderId(),customerContract.getCustomerId(),customerContract.getPaymentMethod());
                    insertMessage(customerContract.getContractNumber());
                    //如果是补款升级合同需要把原来订单产品的会员卡进行作废

                    if("1".equals(customerContract.getContractOtherType())){
                        String upgradeRelateFinishProductId = customerContract.getUpgradeRelateFinishProductId();
                        FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(upgradeRelateFinishProductId);
                        customerProductOrderService.backProduct(finishOrderProduct.getProductOrderId(),finishOrderProduct.getFinishOrderProductNum());
                    }

                    List<FinishOrderProduct> finishOrderProducts = finishOrderDBservice.selectFinishOrderProductList("1", customerContract.getOrderId());
                    CustomerProductOrderVO order = customerProductOrderService.getOrderInfoById(customerContract.getOrderId());
                    if(finishOrderProducts != null && finishOrderProducts.size() > 0){
                        for(FinishOrderProduct finish : finishOrderProducts) {
                            returnMoneyService.reqCrm(order,finish.getProductCode(),"1",finish.getProductFinalPrice(),userAccount,finish.getFinishOrderProductNum());
                        }
                    }




                    break;
                }
/*                case "4": {
                    //插入回款表
                    returnMoney(customerContract.getContractType(),contractReceivables,customerContract.getContractId(),
                            customerContract.getOrderId(),customerContract.getCustomerId());
                    //发送回款消息
                    insertMessage(customerContract.getContractNumber());
                    break;
                }*/
            }
        }

        if(customerContract.getContractActualTotalAmount()!=null){
            //如果是线下支付且合同总金额为0
            if((PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(customerContract.getPaymentMethod()))&&("2".equals(contractReviewQO.getProcessResult())||"4".equals(contractReviewQO.getProcessResult()))&&BigDecimal.ZERO.compareTo(customerContract.getContractActualTotalAmount())==0){
                //插入回款表
                returnMoney(customerContract.getContractType(),contractReceivables,customerContract.getContractId(),
                        customerContract.getOrderId(),customerContract.getCustomerId(),customerContract.getPaymentMethod());
                insertMessage(customerContract.getContractNumber());
                //如果是补款升级合同需要把原来订单产品的会员卡进行作废

                if("1".equals(customerContract.getContractOtherType())){
                    String upgradeRelateFinishProductId = customerContract.getUpgradeRelateFinishProductId();
                    FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(upgradeRelateFinishProductId);
                    customerProductOrderService.backProduct(finishOrderProduct.getProductOrderId(),finishOrderProduct.getFinishOrderProductNum());
                }

                List<FinishOrderProduct> finishOrderProducts = finishOrderDBservice.selectFinishOrderProductList("1", customerContract.getOrderId());
                CustomerProductOrderVO order = customerProductOrderService.getOrderInfoById(customerContract.getOrderId());
                if(finishOrderProducts != null && finishOrderProducts.size() > 0){
                    for(FinishOrderProduct finish : finishOrderProducts) {
                        returnMoneyService.reqCrm(order,finish.getProductCode(),"1",finish.getProductFinalPrice(),userAccount,finish.getFinishOrderProductNum());
                    }
                }

            }
        }

        return result;
    }

    /***
     * @Description:下订单后余额支付全额回款
     * @Param:contractId 合同id
     * @Param:orderId 订单id
     * @Author: luojie
     * @Date: 2021/9/7 9:16
     */
    public void returnMoney(String contractType,BigDecimal contractReceivables,String contractId,String orderId,String customerId,String paymentMethod){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        CustomerProductOrder order = orderDbService.selectCustomerProductOrderById(orderId);

        ReturnMoney returnMoney = new ReturnMoney();
        Date arriveTime = new Date();
        returnMoney.setArriveTime(arriveTime);
        //全额回款
        returnMoney.setArriveType(0);

        if(PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)){
            //线下支付
            returnMoney.setArriveMethod(1);
        }else{
            //余额支付
            returnMoney.setArriveMethod(2);
        }

        //订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:兑换类型;5:补款升级
        for (int i=1;i<6;i++){
            //赠品活动3不插入回款表,兑换类型4暂时还没有做
            if (i == 3 || i ==4){
                continue;
            }
            //查询finish表所有产品（不含赠品）
            List<FinishOrderProduct> finishList = finishOrderDBservice.selectFinishOrderProductList(String.valueOf(i),null,orderId);
            for (int k=0;k<finishList.size();k++){
                //到款编号
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveNum("RM"+new Date().getTime());
                BigDecimal productFinalPrice = finishList.get(k).getProductFinalPrice();
                returnMoney.setArriveMoney(productFinalPrice);
                returnMoney.setProductId(finishList.get(k).getProductId());
                returnMoney.setProductNumber(finishList.get(k).getProductCode());
                returnMoney.setProductName(finishList.get(k).getProductName());
                returnMoney.setProductCategories(finishList.get(k).getProductCategories());
                returnMoney.setFinishOrderProductId(finishList.get(k).getFinishOrderProductId());
                returnMoney.setFinishOrderProductNum(finishList.get(k).getFinishOrderProductNum());
                returnMoney.setOrderDetailType(finishList.get(k).getOrderDetailType());
                returnMoney.setContractType(finishList.get(k).getContractType());
                //续费合同开始日期
                if("4".equals(customerContract.getContractType())){
                    returnMoney.setRenewContractStartTime(customerContract.getContractStartDate());
                }
                returnMoney.setContractId(contractId);
                returnMoney.setContractNumber(customerContract.getContractNumber());
                returnMoney.setCustomerId(customerContract.getCustomerId());
                returnMoney.setCustomerName(customerContract.getCustomerName());
                returnMoney.setOrderId(finishList.get(k).getProductOrderId());
                returnMoney.setOrderNumber(order.getOrderNumber());
                returnMoney.setSalesmanId(finishList.get(k).getCreatePeopleId());
                returnMoney.setFilialeId(finishList.get(k).getCompanyId());
                returnMoney.setCreateTm(new Date());
                returnMoney.setCreateBy(userAccount.getAccountId());
                returnMoney.setUpdateTm(new Date());
                returnMoney.setUpdateBy(userAccount.getAccountId());
                returnMoney.setDataSource(0);
                if (!StringUtils.isBlank(order.getOrderType())){
                    returnMoney.setVipType(Integer.valueOf(order.getOrderType()));
                }
                //业绩计算比例
                BigDecimal scoreConvertRatio = finishList.get(k).getPerformanceConversionRatio();
                returnMoney.setScoreConvertRatio(scoreConvertRatio);
                //业绩金额
                if(scoreConvertRatio!=null){
                    if (scoreConvertRatio.equals(BigDecimal.ZERO)){
                        //如果业绩比例为0，业绩金额为负应收款
                        if(productFinalPrice!=null){
                            returnMoney.setScoreMoney(productFinalPrice.multiply(new BigDecimal(-1)));
                        }else{
                            returnMoney.setScoreMoney(BigDecimal.ZERO);
                        }
                    }else if(scoreConvertRatio.equals(new BigDecimal(1))){
                        //如果业绩比例为1，业绩金额为0
                        returnMoney.setScoreMoney(BigDecimal.ZERO);
                    }else {
                        if(productFinalPrice!=null){
                            //如果业绩比例为小于1，业绩金额为 （负的（应收款-应收款*业绩比例））
                            returnMoney.setScoreMoney((productFinalPrice.subtract(productFinalPrice.multiply(scoreConvertRatio)).multiply(new BigDecimal(-1))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }else{
                            returnMoney.setScoreMoney(BigDecimal.ZERO);
                        }

                    }
                    //插入回款表
                    returnMoneyDbservice.addReturnMoney(returnMoney);
                    returnMoneyRedisService.delReturnMoney(arriveTime, userAccount.getCompanyId(), productFinalPrice, returnMoney.getScoreMoney());

                    String upgradeRelateFinishProductId = customerContract.getUpgradeRelateFinishProductId();
                    if(!StringUtils.isBlank(upgradeRelateFinishProductId)){
                    FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinishOrderProductById(upgradeRelateFinishProductId);
                        //判断是不是补款升级合同
                        if("1".equals(customerContract.getContractOtherType())&&scoreConvertRatio.compareTo(finishOrderProduct.getPerformanceConversionRatio())!=0){
                            //是补款升级合同且业绩比例不相等需要补业绩
                            //String oldContractId = customerContract.getUpgradeRelateContract();
                            //CustomerContract oldContract = customerContractDbService.selectContractById(oldContractId);

                            returnMoney.setArriveTime(new Date());
                            returnMoney.setArriveMoney(BigDecimal.ZERO);
                            returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                            returnMoney.setArriveNum("TRM"+new Date().getTime());
                            returnMoney.setCreateTm(new Date());
                            returnMoney.setUpdateTm(new Date());
/*                            returnMoney.setProductId(finishOrderProduct.getProductId());
                            returnMoney.setProductNumber(finishOrderProduct.getProductCode());
                            returnMoney.setProductName(finishOrderProduct.getProductName()+"(调减业绩-" + finishList.get(k).getProductName() + " " + finishList.get(k).getProductCode()+")");
                           // returnMoney.setProductCategories(finishOrderProduct.getProductCategories());
                            returnMoney.setFinishOrderProductId(finishOrderProduct.getFinishOrderProductId());
                            returnMoney.setFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());
                            returnMoney.setOrderDetailType(finishOrderProduct.getOrderDetailType());
                            returnMoney.setContractType(finishOrderProduct.getContractType());
                           //续费合同开始日期
                            if("4".equals(customerContract.getContractType())){
                                returnMoney.setRenewContractStartTime(oldContract.getContractStartDate());
                            }
                            returnMoney.setContractId(oldContractId);
                            returnMoney.setContractNumber(oldContract.getContractNumber());
                            returnMoney.setCustomerId(oldContract.getCustomerId());
                            returnMoney.setCustomerName(oldContract.getCustomerName());
                            returnMoney.setOrderId(finishOrderProduct.getProductOrderId());
                            returnMoney.setOrderNumber(finishOrderProduct.getOrderNumber());
                            returnMoney.setSalesmanId(oldContract.getCreatePeopleId());
                            returnMoney.setFilialeId(oldContract.getAffiliationCompanyId());
                            returnMoney.setUpdateBy(userAccount.getAccountId());
                            returnMoney.setDataSource(0);
                            returnMoney.setCreateBy(userAccount.getAccountId());
                            if (!StringUtils.isBlank(order.getOrderType())){
                                returnMoney.setVipType(Integer.valueOf(oldContract.getWhetherCheck()));
                            }*/
                            //对比业绩比,如果补款升级产品业绩比例比原来产品高则需要插入正的原来业绩金额*（补款升级业绩比例-原来业绩比例），
                            //如果比原来低需要插入负原来业绩金额*（原来业绩比例-补款升级业绩比例）
                            //if(scoreConvertRatio.compareTo(finishOrderProduct.getPerformanceConversionRatio())==1){
                            BigDecimal scoreRatio = scoreConvertRatio.subtract(finishOrderProduct.getPerformanceConversionRatio());
                            returnMoney.setScoreConvertRatio(scoreRatio);
                            returnMoney.setScoreMoney((finishOrderProduct.getProductFinalPrice().multiply(scoreConvertRatio.subtract(finishOrderProduct.getPerformanceConversionRatio()))).setScale(2, BigDecimal.ROUND_HALF_UP));
/*                            }else if(scoreConvertRatio.compareTo(finishOrderProduct.getPerformanceConversionRatio())==-1){
                                returnMoney.setScoreMoney((finishOrderProduct.getProductFinalPrice().multiply(finishOrderProduct.getPerformanceConversionRatio().subtract(scoreConvertRatio)).multiply(new BigDecimal(-1))).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }*/
                            returnMoneyDbservice.addReturnMoney(returnMoney);
                            returnMoneyRedisService.delReturnMoney(arriveTime, userAccount.getCompanyId(),BigDecimal.ZERO , returnMoney.getScoreMoney());
                        }
                    }
                }
                /*else if("1".equals(customerContractAddQO.getWhetherCooperateDevelopment())&&scoreConvertRatio!=null){
                    List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contractId);
                    for (int p=0;p < developerList.size();p++){
                        CustomerContractDeveloper customerContractDeveloper = developerList.get(p);
                        UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(customerContractDeveloper.getCoDeveloper());
                        if (Objects.nonNull(returnMoney.getScoreMoney())){
                            returnMoney.setScoreMoney(customerContractDeveloper.getAllocationMount().multiply(scoreConvertRatio).multiply(customerContractDeveloper.getAllocationRatio()).multiply(new BigDecimal(-1)));
                        }

                        if (scoreConvertRatio.equals(BigDecimal.ZERO)){
                            //如果业绩比例为0，业绩金额为负应收款
                            returnMoney.setScoreMoney(customerContractDeveloper.getAllocationMount().multiply(customerContractDeveloper.getAllocationRatio()).multiply(new BigDecimal(-1)));
                        }else if(scoreConvertRatio.equals(new BigDecimal(1))){
                            //如果业绩比例为1，业绩金额为0
                            returnMoney.setScoreMoney(BigDecimal.ZERO);
                        }else {
                            //如果业绩比例为小于1，业绩金额为 （负的（应收款-应收款*业绩比例））
                            returnMoney.setScoreMoney((customerContractDeveloper.getAllocationMount().subtract(productFinalPrice.multiply(scoreConvertRatio))).multiply(customerContractDeveloper.getAllocationRatio()).multiply(new BigDecimal(-1)));
                        }

                        returnMoney.setSalesmanId(developerUser.getAccountId());
                        returnMoney.setFilialeId(developerUser.getCompanyId());
                        //插入回款表
                        returnMoneyDbservice.addReturnMoney(returnMoney);
                        //删除redis业绩统计
                        returnMoneyRedisService.delReturnMoney(arriveTime, developerUser.getCompanyId(), customerContractDeveloper.getAllocationMount(), returnMoney.getScoreMoney());
                    }
                }*/


                //更新Finish表的产品状态为已回款
                FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
                finishOrderProduct.setFinishOrderProductId(finishList.get(k).getFinishOrderProductId());
                finishOrderProduct.setProductStatus("3");
                finishOrderDBservice.updateFinishOrderProduct(finishOrderProduct);
            }
        }

        //更新订单表
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(orderId);
        customerProductOrder.setPaidBackAmount(contractReceivables);
        //设置订单为已完成
        customerProductOrder.setOrderStatus("2");
        customerProductOrder.setOrderCompleteTm(new Date());
        //更新订单表
        productOrderDbService.updateByPrimaryKeySelective(customerProductOrder);


        //更新合同表
        CustomerContract customerContractUpdate = new CustomerContract();
        customerContractUpdate.setContractId(contractId);
        customerContractUpdate.setContractTotalPaymentAmount(contractReceivables);
        //回款次数
        customerContractUpdate.setPaymentNumber(1);
        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        customerContractUpdate.setContractStatus("2");
        //回款状态：0-未回款；1-已回款；3-部分回款
        customerContractUpdate.setPaymentStatus("1");
        customerContractUpdate.setPaymentDate(new Date());
        //更新合同
        customerContractDbService.updateCustomerContract(customerContractUpdate);

        //维护客户表会员到期时间、会员开始时间、客户状态、会员等级
        // 2、4为会员合同
        if ("2".equals(contractType) || "4".equals(contractType)){
            CustomerContract contract = new CustomerContract();
            contract.setCustomerId(customerId);
            returnMoneyService.updateCustomer(contract);
        }
    }

    /***
     * @Description:合同回款完发送消息
     * @Param: contractNumber 合同编号
     * @Author: luojie
     * @Date: 2021/9/7 22:18
     */
    public void insertMessage(String contractNumber){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //插入消息提示表
        MessagePrompt messagePrompt = new MessagePrompt();
        messagePrompt.setMessageId(CommonUtils.getGUID());
        //消息类型为审核
        messagePrompt.setMessageType(Short.parseShort("2"));
        messagePrompt.setMessageState(Short.parseShort("0"));
        messagePrompt.setMessageContent("您的合同编号：" + contractNumber + "已回款完成");
        messagePrompt.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        messagePrompt.setCreatePeopleId(userAccount.getAccountId());
        messagePrompt.setCreateTm(new Date());
        messagePrompt.setUpdatePeopleId(userAccount.getAccountId());
        messagePrompt.setUpdateTm(new Date());
        messagePromptDbService.insertMessagePrompt(messagePrompt);
    }

    /**
     * 新增回款
     *
     * @param returnList   回款列表
     * @param contractId   合同id
     * @param orderId      订单id
     * @param customerId   客户id
     * @param contractType 合同类型
     */
    public void insertReturnMoney(List<HashMap> returnList, String contractId, String orderId, String customerId, String contractType) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        for (HashMap returnMoney : returnList) {
            ReturnMoney returnMoneyNew = new ReturnMoney();
            returnMoneyNew.setArriveTime(new Date());
            returnMoneyNew.setArriveMoney((BigDecimal) returnMoney.get("amount"));
            returnMoneyNew.setArriveMethod(Integer.parseInt(returnMoney.get("paymentMethod").toString()));
            returnMoneyNew.setOrderId(orderId);
            //提成发放状态-转入额的提成发放状态是已全部发放，余额的提成发放状态是全部发放
            if("2".equals(returnMoney.get("paymentMethod").toString())){
                returnMoneyNew.setRoyaltyStatus(3);
            }else if("4".equals(returnMoney.get("paymentMethod").toString())){
                returnMoneyNew.setRoyaltyStatus(1);
            }
            returnMoneyService.addReturnMoney(returnMoneyNew,0,false);
        }

/*        //新增FinishProduct表
        List<FinishOrderProduct> finishList = productOrderDbService.getFinishProductList(orderId, 0);
        ReturnMoneyServiceImpl returnMoneyServiceImpl = new ReturnMoneyServiceImpl();
        if (finishList.size() > 0) {
            returnMoneyService.addFinishProductList(finishList, 0, contractType);
        }*/

    }

    public void updateOrderAndContract(String contractId,String orderId,BigDecimal contractReceivables){
        //更新订单表
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(orderId);
        customerProductOrder.setPaidBackAmount(contractReceivables);
        //订单状态设置为已完成 订单状态--1:等待回款;2:已完成;3:作废;4:部分回款
        customerProductOrder.setOrderStatus("2");
        customerProductOrder.setOrderCompleteTm(new Date());
        productOrderDbService.updateProductOrder(customerProductOrder);

        //更新合同
        CustomerContract contract = new CustomerContract();
        contract.setContractId(contractId);
        contract.setContractTotalPaymentAmount(contractReceivables);
        //合同回款次数
        contract.setPaymentNumber(1);
        //合同状态设置为成效中
        contract.setContractStatus("2");
        //合同回款状态为已回款
        contract.setPaymentStatus("1");
        customerContractDbService.updateCustomerContract(contract);
    }

    /***
     * @Description: 根据合同id获取合同审核结果List
     * @Param: contractId 合同id
     * @Author: luojie
     * @Date: 2021/3/31 11:44
     */
    @Override
    public DhPageInfo<ContractReviewResultListVO> getContractReviewResultList(String contractId,Integer pageIndex,Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //获取审核详情
        List<ContractReviewResultListVO> contractReviewResultListVOList = new ArrayList<>();
        List<ContractReview> contractReviews = contractReviewDbService.selectContractReviewListByContractId(contractId);
        PageInfo<ContractReview> pageInfo = new PageInfo<>(contractReviews);
        for (ContractReview contractReview : pageInfo.getList()) {
            ContractReviewResultListVO contractReviewResultListVO = new ContractReviewResultListVO();
            contractReviewResultListVO.setContractReviewId(contractReview.getContractReviewId());
            contractReviewResultListVO.setCreateTm(contractReview.getCreateTm());
            if(StringUtils.isBlank(contractReview.getContractReviewNotes())){
                contractReviewResultListVO.setContractReviewNotes("无");
            }else {
                contractReviewResultListVO.setContractReviewNotes(contractReview.getContractReviewNotes());
            }

            //查询创建人姓名
            UserAccount userAccount = accountDbService.selectUserAccountByAccountId(contractReview.getCreatePeopleId());
            contractReviewResultListVO.setCreatePeopleName(userAccount.getUserName());
            //查询审核不符类型
            if(!StringUtils.isBlank(contractReview.getContractReviewType())){
                switch(contractReview.getContractReviewType()){
                    case "1" :
                        contractReviewResultListVO.setContractReviewTypeName("联系人/联系方式不准确");
                        break;
                    case "2" :
                        contractReviewResultListVO.setContractReviewTypeName("跟进记录/商机不符");
                        break;
                    case "3" :
                        contractReviewResultListVO.setContractReviewTypeName("合同日期不对");
                        break;
                    case "4" :
                        contractReviewResultListVO.setContractReviewTypeName("合同款项不正确");
                        break;
                    case "5" :
                        contractReviewResultListVO.setContractReviewTypeName("回款关联有误");
                        break;
                    case "6" :
                        contractReviewResultListVO.setContractReviewTypeName("优惠特批未通过");
                        break;
                    case "7" :
                        contractReviewResultListVO.setContractReviewTypeName("合同类型不符");
                        break;
                    default :
                        contractReviewResultListVO.setContractReviewTypeName("—");
                }
            }

            if(!StringUtils.isBlank(contractReview.getProcessResult())){
                //处理结果
                switch(contractReview.getProcessResult()){
                    case "1" :
                        contractReviewResultListVO.setProcessResultName("补充材料");
                        break;
                    case "2" :
                        contractReviewResultListVO.setProcessResultName("通过");
                        break;
                    case "3" :
                        contractReviewResultListVO.setProcessResultName("未通过");
                        break;
                    case "4" :
                        contractReviewResultListVO.setProcessResultName("通过并盖章");
                        break;
                    default :
                        contractReviewResultListVO.setProcessResultName("");
                }
            }
            contractReviewResultListVOList.add(contractReviewResultListVO);
        }
        return new DhPageInfo<ContractReviewResultListVO>(pageInfo, contractReviewResultListVOList);
    }

    /***
     * @Description: 查询客户下的优惠券
     * @Param: customerId 客户id
     * @Author: baijian
     * @Date: 2021/11/15 10:54
     */
    @Override
    public DhPageInfo<ContractCouponVO> contractCouponList(String customerId,Integer pageIndex,Integer pageSize,String sortName,String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<ContractCouponVO> list = contractReviewDbService.contractCouponList(customerId);
        PageInfo<ContractCouponVO> pageInfo = new PageInfo<ContractCouponVO>(list);
        return new DhPageInfo<ContractCouponVO>(pageInfo, list);
    }

    /**
     * 使用优惠券
     */
    @Override
    public Boolean couponUse(String couponId,String couponCode) {

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", couponCode);
        log.info("请求数据---"+paramMap);
        String res= HttpUtil.post("https://api.nsrjlb.com/crm/ExchangeCode/changeCoupon", paramMap);
        log.info("返回数据---"+res);


        CustomerProductDetailCoupon coupon = new CustomerProductDetailCoupon();
        coupon.setCouponId(couponId);
        coupon.setUseType(1);
        return customerSendCodeDbService.updateCustomerProductDetailCoupon(coupon);
    }
}
